package com.bosssoft.g1.authserver.config;

import com.bosssoft.g1.authserver.component.JwtTokenEnhancer;
import com.bosssoft.g1.authserver.service.UserServiceImpl;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.rsa.crypto.KeyStoreKeyFactory;
import tk.mybatis.spring.annotation.MapperScan;

import java.security.KeyPair;
import java.util.ArrayList;
import java.util.List;

/**
 * 认证服务器配置
 * Created by macro on 2020/6/19.
 */
@AllArgsConstructor
@Configuration
@EnableAuthorizationServer
@MapperScan({"com.bosssoft.g1.authserver.mapper"})
public class Oauth2ServerConfig extends AuthorizationServerConfigurerAdapter {
    // 密码编码器，用于客户端密码加密
    private final PasswordEncoder passwordEncoder;
    // 用户服务，提供用户详情
    private final UserServiceImpl userDetailsService;
    // 认证管理器，处理用户认证
    private final AuthenticationManager authenticationManager;
    // JWT增强器，用于自定义JWT内容
    private final JwtTokenEnhancer jwtTokenEnhancer;

    /**
     * 配置客户端详细信息服务
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("client-app") // 客户端ID
                .secret(passwordEncoder.encode("123456")) // 客户端密钥
                .scopes("all") // 授权范围
                .authorizedGrantTypes("password", "refresh_token") // 授权类型，只使用密码模式和刷新令牌
                .accessTokenValiditySeconds(360000) // 访问令牌有效期（秒）
                .refreshTokenValiditySeconds(864000); // 刷新令牌有效期（秒）
    }

    /**
     * 配置授权和令牌的访问端点和令牌服务
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        // 配置JWT的内容增强器
        TokenEnhancerChain enhancerChain = new TokenEnhancerChain();
        List<TokenEnhancer> delegates = new ArrayList<>();
        delegates.add(jwtTokenEnhancer);
        delegates.add(accessTokenConverter());
        enhancerChain.setTokenEnhancers(delegates);

        endpoints.authenticationManager(authenticationManager) // 配置认证管理器
                .userDetailsService(userDetailsService) // 配置用户详情服务
                .accessTokenConverter(accessTokenConverter()) // 配置访问令牌转换器
                .tokenEnhancer(enhancerChain); // 配置令牌增强链
    }

    /**
     * 配置授权服务器的安全性
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        // 允许客户端表单身份验证
        security.allowFormAuthenticationForClients();
    }

    /**
     * 配置JWT访问令牌转换器的Bean
     */
    @Bean
    public JwtAccessTokenConverter accessTokenConverter() {
        JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
        // 配置JWT使用的密钥对
        jwtAccessTokenConverter.setKeyPair(keyPair());
        return jwtAccessTokenConverter;
    }

    /**
     * 从classpath下的证书中获取密钥对的Bean
     */
    @Bean
    public KeyPair keyPair() {
        // 从classpath下的证书文件(jwt.jks)中获取密钥对
        KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(new ClassPathResource("jwt.jks"), "123456".toCharArray());
        return keyStoreKeyFactory.getKeyPair("jwt", "123456".toCharArray());
    }
}
